package com.wenyu.wenyuyuedu.fragment.homepagefragment;


import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.jingchen.pulltorefresh.PullableListView;
import com.wenyu.wenyuyuedu.R;
import com.wenyu.wenyuyuedu.activity.LoginActivity;
import com.wenyu.wenyuyuedu.activity.homepage.MyAttentionActivity;
import com.wenyu.wenyuyuedu.adapter.homepagefragment.AllAttenAdapter;
import com.wenyu.wenyuyuedu.bean.homepager.AllAttentionBean;
import com.wenyu.wenyuyuedu.global.ApiWrapper;
import com.wenyu.wenyuyuedu.server.homepager.Home_AllAtten_Server;
import com.wenyu.wenyuyuedu.utils.AbSharedUtil;
import com.wenyu.wenyuyuedu.utils.MyToast;
import com.wenyu.wenyuyuedu.utils.SharedConstants;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static anetwork.channel.http.NetworkSdkSetting.context;

/**
 * A simple {@link Fragment} subclass.
 * 全部关注
 */
public class AllAttentionFragment extends Fragment {


    @InjectView(R.id.allattention_content_view)
    PullableListView allattentionContentView;
    @InjectView(R.id.allattention_refresh_view)
    PullToRefreshLayout allattentionRefreshView;
    @InjectView(R.id.iv_defult)
    ImageView ivDefult;
    @InjectView(R.id.rl_default)
    RelativeLayout rlDefault;
    private View allAttention;
    private ListView pullableView;
    private String token;
    private int page = 1;
    private List<AllAttentionBean.InfoBean> infoAttention;
    private List<AllAttentionBean.InfoBean> infoAll = new ArrayList<>();
    private boolean isLoading = false;
    private AllAttenAdapter allAttenAdapter;
    private Intent intent;

    public AllAttentionFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        allAttention = inflater.inflate(R.layout.fragment_all_attention, container, false);
        ButterKnife.inject(this, allAttention);
        intent = new Intent();
        allAttenAdapter = new AllAttenAdapter(getActivity());
        allattentionContentView.setAdapter(allAttenAdapter);
        initPutoRefresh();
        return allAttention;
    }
    @Override
    public void onStart() {
        super.onStart();
        isLoading = false;
        request();
    }
    /*
            * 初始化网络数据
            * */
    private void request() {
        token = AbSharedUtil.getString(getActivity(), SharedConstants.USER_TOKEN);
        Home_AllAtten_Server home_allAtten_server = ApiWrapper.getInstance().create(Home_AllAtten_Server.class);
        final Call<AllAttentionBean> index = home_allAtten_server.getIndex(token, page, 2);
        index.enqueue(new Callback<AllAttentionBean>() {
            @Override
            public void onResponse(Call<AllAttentionBean> call, Response<AllAttentionBean> response) {
                AllAttentionBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    if (code == 1) {
                        if (body.getInfo() != null) {
                            infoAttention = body.getInfo();
                            if (!isLoading) {
                                infoAll.clear();
                                allAttenAdapter.clear();
                            }
                            infoAll.addAll(infoAttention);
                            allAttenAdapter.AddAll(infoAll);
                            ivDefult.setVisibility(View.GONE);
                            rlDefault.setVisibility(View.GONE);
                        } else {
                            ivDefult.setVisibility(View.VISIBLE);
                        }
                    } else if (code == 0) {
                        //showLoginDoalog();
                        ivDefult.setVisibility(View.VISIBLE);
                    } else if (code == 2103) {
                        //暂未加入圈子
                        rlDefault.setVisibility(View.VISIBLE);
                        if(infoAll != null && allAttenAdapter != null){
                            infoAll.clear();
                            allAttenAdapter.notifyDataSetChanged();
                        }
                    } else if (code == 2100) {
                        MyToast.showToast(getActivity(), "所有数据加载完毕", Toast.LENGTH_SHORT);
                    }
                } else {
                    ivDefult.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFailure(Call<AllAttentionBean> call, Throwable t) {
                ivDefult.setVisibility(View.VISIBLE);
                //   MyToast.showToast(getActivity(), "网络异常，请稍后重试", Toast.LENGTH_SHORT);
            }
        });
    }

    /*
    * 初始化刷新的控件
    * */
    private void initPutoRefresh() {
        pullableView = (ListView) allattentionRefreshView.getPullableView();
        allattentionRefreshView.setOnPullListener(new PullToRefreshLayout.OnPullListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                new Handler() {
                    public void handleMessage(Message msg) {
                        page = 1;
                        isLoading = false;
                        request();
                        //千万别忘了告诉控件刷新完毕了
                        allattentionRefreshView.refreshFinish(PullToRefreshLayout.SUCCEED);
                    }
                }.sendEmptyMessageDelayed(0, 1000);
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                new Handler() {
                    public void handleMessage(Message msg) {
                        page++;
                        isLoading = true;
                        request();

                        //千万别忘了告诉控件刷新完毕了
                        allattentionRefreshView.refreshFinish(PullToRefreshLayout.SUCCEED);
                    }
                }.sendEmptyMessageDelayed(0, 1000);
            }
        });
        allattentionContentView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), MyAttentionActivity.class);
                AllAttentionBean.InfoBean infoBean = allAttenAdapter.getInfo().get(i);
                String title = infoBean.getTitle();
                String id = infoBean.getId();
                String nickname = infoBean.getNickname();
                intent.putExtra("allattentionnickname", nickname);
                intent.putExtra("allattentionid", id);
                intent.putExtra("allattentiontitle", title);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    /*token错误或失效*/
    AlertDialog ad;
    private TextView quxiao;
    private TextView queding;

    private void showLoginDoalog() {

        ad = new AlertDialog.Builder(getActivity()).create();
        ad.show();
        Window window = ad.getWindow();
        window.setContentView(R.layout.dailog_login);
        quxiao = (TextView) window.findViewById(R.id.dialog_login_quxiao);
        queding = (TextView) window.findViewById(R.id.dialog_login_queding);
        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AbSharedUtil.putString(context, SharedConstants.USER_TOKEN, "");

                intent.setClass(getActivity(), LoginActivity.class);
                startActivity(intent);
                ad.dismiss();
            }
        });
    }

}
